package com.grm.sys.service.impl;

import com.grm.common.exception.BusinessException;
import com.grm.sys.mapper.SysDictDataMapper;
import com.grm.sys.model.SysDictData;
import com.grm.sys.model.SysDictType;
import com.grm.sys.request.dict.data.SysDictDataAddParam;
import com.grm.sys.request.dict.data.SysDictDataQueryParam;
import com.grm.sys.request.dict.data.SysDictDataUpdateParam;
import com.grm.sys.service.SysDictDataService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysDictDataServiceImpl implements SysDictDataService {
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public List<SysDictData> querySelectByType(String type) {
        return sysDictDataMapper.queryByType(type);
    }

    @Override
    public List<SysDictData> querySelective(SysDictDataQueryParam queryParam) {
        return sysDictDataMapper.querySelective(queryParam);
    }

    @Override
    public void delete(List<Long> ids) {
        if (ObjectUtils.isNotEmpty(ids)) {
            sysDictDataMapper.deleteByIds(ids);
        }
    }

    @Override
    public void add(SysDictDataAddParam addParam) {
        SysDictData dbSysDictData = sysDictDataMapper.queryByTypeAndKey(addParam.getType(),addParam.getKey());
        if(dbSysDictData != null){
            throw new BusinessException("字典已存在！");
        }
        // copyBean
        SysDictData sysDictData = new SysDictData();
        BeanUtils.copyProperties(addParam, sysDictData);
        sysDictDataMapper.insert(sysDictData);
    }

    @Override
    public void update(SysDictDataUpdateParam updateParam) {
        SysDictData dbSysDictData = sysDictDataMapper.queryById(updateParam.getId());
        // 判断修改后的key数据库有没有，如果有，抛出异常，key已存在
        SysDictData dbSysDictData2 = sysDictDataMapper.queryByTypeAndKey(updateParam.getType(),updateParam.getKey());
        if(dbSysDictData2 != null && !dbSysDictData2.getId().equals(dbSysDictData.getId())){
            throw new BusinessException("字典数据key已存在！");
        }
        // copyBean
        SysDictData sysDictData = new SysDictData();
        BeanUtils.copyProperties(updateParam, sysDictData);
        sysDictDataMapper.update(sysDictData);
    }
}
